package com.itwlj.controller.admin;

import com.itwlj.constant.MessageConstant;
import com.itwlj.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Value("${mall.path}")
    private String basePath;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            file.transferTo(new File(basePath + objectName));
            //文件的请求路径
            String filePath = "http://localhost:8080/images/" + objectName;
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    @PostMapping("/sms/send")
    @ApiOperation("发送手机验证码")
    public Result<String> sendSms(String phone) {
        log.info("发送手机验证码,手机号：{}", phone);

        String captcha = generateCaptcha();
        System.out.println("验证码="+captcha);
        redisTemplate.opsForValue().set(phone, captcha, 60, TimeUnit.SECONDS);

        return Result.success();
    }

    // 生成6位数字验证码
    public String generateCaptcha() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));  // 生成0到9的随机数字
        }
        return code.toString();
    }
}
